组件生命周期函数
万物皆有生命周期。人的生命周期,分别有婴儿期,成熟期、晚年期,在不同的生命时期里所做的工作是不一样的,组件也有生命周期,如下:
<script>
import {
createComponent,
onMounted,
onUpdated,
onUnmounted
} from '@vue/composition-api' //导入相应的生命周期函数
export default createComponent({
setup() {
onMounted(() => {
console.log('mounted!')
})
onUpdated(() => {
console.log('updated!')
})
onUnmounted(() => {
console.log('unmounted!')
})
}
})
</script>
下面是 2.x Options 和 Composition API 的生命周期对照表:
beforeCreate-> use setup()created-> use setup()- beforeMount -> onBeforeMount
- mounted -> onMounted
- beforeUpdate -> onBeforeUpdate
- updated -> onUpdated
- beforeDestroy -> onBeforeUnmount
- destroyed -> onUnmounted
- errorCaptured -> onErrorCaptured